package com.atguigu.tingshu.payment.strategy.impl;

import com.atguigu.tingshu.account.client.RechargeInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.strategy.WeChatPayStrategy;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class RechargeWeChatPayStrategy implements WeChatPayStrategy {

    @Autowired
    private RechargeInfoFeignClient rechargeInfoFeignClient ;

    @Autowired
    private PaymentInfoService paymentInfoService ;

    @Autowired
    private RSAAutoCertificateConfig rsaAutoCertificateConfig ;

    @Autowired
    private WxPayV3Config wxPayV3Config ;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient ;

    @Transactional
    @Override
    public WeChatPayVo createJsapi(String paymentType, String orderNo) {

        // 根据订单的编号查询充值记录
        Result<RechargeInfo> rechargeInfoResult = rechargeInfoFeignClient.getRechargeInfoByOrderNo(orderNo);
        RechargeInfo rechargeInfo = rechargeInfoResult.getData();
        paymentInfoService.savePaymentInfo(rechargeInfo);

        // 请求微信支付平台的下单接口
        WeChatPayVo weChatPayVo = this.wxCreateJsapi(userInfoFeignClient, rsaAutoCertificateConfig, wxPayV3Config, "充值" + rechargeInfo.getRechargeAmount() + "元",
                orderNo, 1);

        // 返回
        return weChatPayVo;
    }

    @Override
    public String getPaymentType() {
        return SystemConstant.PAYMENT_TYPE_RECHARGE;
    }

}
